package threads.threadlocal;

import lombok.SneakyThrows;

import java.util.concurrent.TimeUnit;

public class Demo03 {

    public static void main(String[] args) throws InterruptedException {
        for (int i = 0; i < 20; i++) {
            Thread thread = new ThreadLocalTestThread();
            thread.setName(String.format("测试线程" + i));
            thread.start();
        }

        TimeUnit.SECONDS.sleep(5);
        System.gc();

        TimeUnit.SECONDS.sleep(300);
    }


    static class ThreadLocalTestThread extends Thread {
        @SneakyThrows
        @Override
        public void run() {
            for (int j = 0; j < 100; j++) {
                ThreadLocal threadLocal = new ThreadLocal<>();
                threadLocal.set(new MyUserInfo());

                // 没有会存在内存泄露
                //threadLocal.remove();
            }
//            TimeUnit.SECONDS.sleep(5);
            System.out.println(this.getName() + ", 执行完成");
        }

        @Override
        protected void finalize() throws Throwable {
            super.finalize();
            System.out.println(this.getName() + " ,被垃圾收集器回收");
        }
    }


    static class MyUserInfo {
        private byte[] data;

        public MyUserInfo() {
            this.data = new byte[1024 * 1024];
        }
    }
}
